﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;

namespace Mvcmediaplayer.Validation
{
    public static class ExtensionMethods
    {
        /// <summary>
        /// Get all validation errors for the given instance
        /// </summary>
        public static IEnumerable<ValidationMessage> GetErrors(this IValidationModel instance)
        {
            var metadataAttrib = instance.GetType().GetCustomAttributes(typeof(MetadataTypeAttribute), true).OfType<MetadataTypeAttribute>().FirstOrDefault();
            var typeObject = metadataAttrib != null ? metadataAttrib.MetadataClassType : instance.GetType();
            var typeProperties = TypeDescriptor.GetProperties(typeObject).Cast<PropertyDescriptor>();
            var classProperties = TypeDescriptor.GetProperties(instance.GetType()).Cast<PropertyDescriptor>();

            return from property in typeProperties
                   join modelProp in classProperties on property.Name equals modelProp.Name
                   from attribute in property.Attributes.OfType<ValidationAttribute>()
                   where !attribute.IsValid(modelProp.GetValue(instance))
                   select new ValidationMessage { PropertyName = property.Name, ErrorMessage = attribute.FormatErrorMessage(string.Empty) };
        }

    }

}